/**
 * @author Shine Chen
 * @date 2011.11.11
 */

package org.mini.templates
{
	import com.shine.crypt.EventDispatcherBase;
	import com.shine.events.CarryEvent;
	import com.shine.utils.DisplayObjectUtil;
	import com.shine.loader.ILoader;
	
	import flash.events.Event;
	
	import org.mini.events.ResizeEvent;
	import org.mini.events.SiteEventTypes;
	
	public class AbstractPage extends AbstractBase
	{
		private var _id:String
		
		protected var _assets:Object;
		protected var _params:Object;
		
		protected var _preloader_class:Class;
		protected var _preloader_instance:AbstractPreloader;
		
		public function AbstractPage()
		{
			super();
		}
		
		public function setup(id:String,assets:Object,params:Object,current:Boolean,c:Class=null):void
		{
			_id=id;
			_assets=assets;
			_params=params;
			_preloader_class=c;
			
			if(current) addSiteListener(SiteEventTypes.PAGE_LOAD_PROGRESS,onProgress);
			addSiteListener(SiteEventTypes.PAGE_LOAD_COMPLETE,onComplete);
		}
		
		override protected function addToStage(e:Event=null):void
		{
			super.addToStage(e);
			EventDispatcherBase.instance.addEventListener(ResizeEvent.SCREEN_RESIZE,resizeHandler);
		}
		
		private function resizeHandler(e:ResizeEvent):void
		{
			resize(e.width,e.height);
		}
		
		protected function resize(w:uint,h:uint):void
		{
			
		}
		
		protected function onProgress(e:CarryEvent):void
		{
			if(_preloader_class && _preloader_instance==null){
				_preloader_instance=new _preloader_class() as AbstractPreloader;
				addChild(_preloader_instance);
			}
			
			if(_preloader_instance) _preloader_instance.updateLoadedPercent(uint(e.value));
		}
		
		public function initialize():void
		{
			if(_preloader_instance && contains(_preloader_instance)) removeChild(_preloader_instance);
		}
		
		private function onComplete(e:Event):void
		{
			initialize();
		}
		
		public function addSiteListener(type:String,fn:Function):void
		{
			EventDispatcherBase.instance.addEventListener((_id+":"+type),fn);
		}
		
		override public function dispose():void
		{
			EventDispatcherBase.instance.removeEventListener(ResizeEvent.SCREEN_RESIZE,resizeHandler);
			EventDispatcherBase.instance.removeListenerById(_id);
			
			DisplayObjectUtil.removeAllChildren(this);
			if(_assets) clearLoader();
			
			_assets=null;
			_params=null;
			
			super.dispose();
		}
		
		private function clearLoader():void
		{
			for(var i:* in _assets){
				var asset:ILoader=_assets[i];
				asset.dispose();
				delete _assets[i];
			}
		}
	}
}